const Router = require('koa-router');

let originPrefix = Router.prototype.prefix;

let originGet = Router.prototype.get;
let originPost = Router.prototype.post;
let originPut = Router.prototype.put;
let originDelete = Router.prototype.delete;
let originAll = Router.prototype.all;

Router.documents = new Map();
Router.prototype.prefix = function (path, description) {
  originPrefix.call(this, path);
  Router.documents.set(path, description);
}

Router.prototype.get = function () {
  let fullPath = `get - ${this.opts.prefix || ''}${arguments[0]}`;

  if (arguments.length > 2) {
    Router.documents.set(fullPath, fillDocument(arguments[2]));
    originGet.apply(this, [arguments[0], arguments[1]]);
  } else {
    originGet.apply(this, arguments);
  }
}

Router.prototype.post = function () {
  let fullPath = `post - ${this.opts.prefix || ''}${arguments[0]}`;

  if (arguments.length > 2) {
    Router.documents.set(fullPath, fillDocument(arguments[2]));
    originPost.apply(this, [arguments[0], arguments[1]]);
  } else {
    originPost.apply(this, arguments);
  }
}

Router.prototype.put = function () {
  let fullPath = `put - ${this.opts.prefix || ''}${arguments[0]}`;

  if (arguments.length > 2) {
    Router.documents.set(fullPath, fillDocument(arguments[2]));
    originPut.apply(this, [arguments[0], arguments[1]]);
  } else {
    originPut.apply(this, arguments);
  }
}

Router.prototype.delete = function () {
  let fullPath = `delete - ${this.opts.prefix || ''}${arguments[0]}`;

  if (arguments.length > 2) {
    Router.documents.set(fullPath, fillDocument(arguments[2]));
    originDelete.apply(this, [arguments[0], arguments[1]]);
  } else {
    originDelete.apply(this, arguments);
  }
}

Router.prototype.all = function () {
  let fullPath = `all - ${this.opts.prefix || ''}${arguments[0]}`;

  if (arguments.length > 2) {
    Router.documents.set(fullPath, fillDocument(arguments[2]));
    originAll.apply(this, [arguments[0], arguments[1]]);
  } else {
    originAll.apply(this, arguments);
  }
}

function fillDocument (doc) {
  let rs = {
    desc: ''
  };

  if (typeof doc == 'string') {
    rs.desc = doc;
  } else {
    let keys = Object.getOwnPropertyNames(doc);

    for (let key of keys) {
      rs[key] = doc[key];
    }
  }

  return rs;
}